<template>
  <div v-loading="isLoading"
       class="video-preView">
    <span class="video-tree">
      <div class="video-tree-input">
        <el-input v-model="monitorSearchValue"
                  placeholder="搜索监控通道" />
        <el-button type="primary"
                   @click="search">搜索</el-button>
      </div>
      <div class="video-device">
        <span class="video-sum-device">设备总数：{{ monitorTotalList.length }}台</span><span class="video-device-list">
          <div style="color: #70B603">在线：{{ monitorTotalList.length }}台</div>
          <div style="color: #D9001B">异常：0台</div>
          <div style="color: #999">离线：0台</div>
        </span>
      </div>
      <div class="monitor-ul">
        <div v-for="(item, $index) in monitorList"
             :key="this"
             :class="item.is_check ? 'monitor-item-active':'monitor-item'"
             @click="monitorBtn(item)">{{ item.name }}</div>
      </div>
      <!-- <el-tree
              :data="data"
              highlight-current
              @node-click="handleNodeClick"
          ></el-tree> -->
    </span><span class="video-play">
      <div class="video-play-select">
        <div class="select-main">方案选择：
          <el-select v-model="planInfo"
                     placeholder="请选择方案"
                     @change="checkPlan">
            <el-option label="请选择方案"
                       value="" />
            <el-option v-for="(item, $index) in planList"
                       :key="item.id"
                       :label="item.name"
                       :value="item">
              <div style="display: flex;justify-content: space-between;align-items: center;">
                <span>{{ item.name }}</span>
                <span style="display: flex;align-items: center;">
                  <i style="cursor: pointer;font-size: 18px;margin-left: 10px;"
                     class="el-icon-edit-outline"
                     @click.stop="editPlan(item, $index)" />
                  <i style="cursor: pointer;font-size: 18px;margin-left: 10px;"
                     class="el-icon-delete"
                     @click.stop="delPlan(item, $index)" />
                </span>
              </div>
            </el-option>
          </el-select>
        </div>
        <el-button type="primary"
                   @click="savePlan">{{ !planInfo ? '保存方案': '更新方案' }}</el-button>
      </div>
      <div id="video-list"
           class="video-list">
        <div id="division"
             :class="segmentation == 4 ? 'division-two': segmentation == 9 ? 'division-three': segmentation == 16 ? 'division-four':'division-five'">
          <div v-for="(item, $index) in monitorArr"
               :class="[monitorIndex === $index ?'monitor-item-active':'', item ? 'monitor-after-none':'']"
               @click="monitorItemBtn($index, 4)"
               @dblclick="monitorCheck(item)" />
        </div>
        <div v-show="isShow"
             id="monitor"
             class="monitor">
          <i class="el-icon-close"
             @click="closeMonitor" />
        </div>
      </div>
      <div class="picture-segmentation">
        <el-popover placement="top-start"
                    title=""
                    width="200"
                    trigger="hover">
          <div class="division-main">
            <div class="division"
                 @click="segmentationBtn(4)">
              <div class="division-two">
                <div v-for="item in 4" />
              </div>
            </div>
            <div class="division"
                 @click="segmentationBtn(9)">
              <div class="division-three">
                <div v-for="item in 9" />
              </div>
            </div>
            <div class="division"
                 @click="segmentationBtn(16)">
              <div class="division-four">
                <div v-for="item in 16" />
              </div>
            </div>
            <div class="division"
                 @click="segmentationBtn(25)">
              <div class="division-five">
                <div v-for="item in 25" />
              </div>
            </div>
          </div>
          <div slot="reference"
               class="segmentation-icon">
            <i class="el-icon-s-grid" />
            <div>画面分割</div>
          </div>
        </el-popover>
      </div>
    </span>
    <el-dialog v-loading="dialogLoading"
               :title="planEdit ? '修改方案' : '新增方案'"
               :visible.sync="dialogVisible"
               width="30%">
      <el-form ref="plan"
               :model="plan"
               label-width="100px">
        <el-form-item label="方案名称"
                      prop="name"
                      :rules="[
            { required: true, message: '请输入方案名称', trigger: 'blur' }
          ]">
          <el-input v-model="plan.name"
                    placeholder="请输入方案名称" />
        </el-form-item>
      </el-form>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="savePlanConfirm('plan')">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import videojs from 'video.js'
import 'video.js/dist/video-js.css'
import 'videojs-contrib-hls'
export default {
  props: {
    name: {
      type: String
    }
  },
  data () {
    return {
      isLoading: false,
      monitorTotalList: [],
      monitorList: [],
      monitorSearchValue: '',
      planList: [],
      options: {
        playbackRates: [0.5, 1.0, 1.5, 2.0], // 播放速度
        // controls: true,
        autoplay: true, // 如果true,浏览器准备好时开始回放。
        muted: false, // 默认情况下将会消除任何音频。
        loop: false, // 导致视频一结束就重新开始。
        preload: 'auto', // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
        language: 'zh-CN',
        aspectRatio: '16:9', // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
        techOrder: ['html5'], // 兼容顺序
        // flash: {
        //     swf: SWF_URL
        // },
        source: {
          type: 'application/x-mpegURL',
          src: 'rtmp://files.meta-720.com:21935/vod/openUrl/5v8wU36'
        },
        poster: '', // 你的封面地址
        notSupportedMessage: '此视频暂无法播放，请稍后再试', // 允许覆盖Video.js无法播放媒体源时显示的默认信息。
        controlBar: {}
      },
      monitorArr: [],
      monitorIndex: '',
      segmentation: 4,
      dialogVisible: false,
      isShow: false,
      plan: {
        name: ''
      },
      dialogLoading: false,
      planEdit: false,
      planInfo: '',
      planIndex: 0,
      hideDropdown: false
    }
  },
  watch: {
    'name': function () {
      if (this.name === 'second') {

      }
    }
  },
  created () {
    this.monitorArr.length = 4
    const monitor = this.$http.get('api/v1/security/monitor')
      .then((res) => {
        this.monitorList = res.data
        this.monitorTotalList = res.data
        this.isLoading = false
      })
      .catch(() => { })
    const plan = this.$http.get('api/v1/security/plan/')
      .then((res) => {
        this.planList = res.data
      })
      .catch(() => { })
    this.isLoading = true
    this.$http.requestAll([monitor, plan])
      .then(() => {
        this.isLoading = false
      })
  },
  beforeDestroy () {
    this.monitorArr.forEach((item, i) => {
      if (item) {
        videojs(`video${i}`, this.options, function () {
          this.dispose()
        })
      }
    })
    if (this.isShow) {
      videojs(`monitor0`, this.options, function () {
        this.dispose()
      })
    }
  },
  methods: {
    init (url) {
      var myVideoDiv = document.getElementById('division').childNodes[this.monitorIndex]
      var tagName = document.createElement('video')
      var sourceTagName = document.createElement('source')
      sourceTagName.setAttribute('src', url)
      sourceTagName.setAttribute('type', 'application/x-mpegURL')
      tagName.className = 'video-js vjs-default-skin vjs-big-play-centered'
      tagName.setAttribute('id', `video${this.monitorIndex}`)
      tagName.appendChild(sourceTagName)
      myVideoDiv.appendChild(tagName)
      videojs(`video${this.monitorIndex}`, this.options, function () {
        this.play()
      })
    },
    monitorBtn (item) {
      if (this.monitorIndex !== '') {
        if (item.is_check) {
          if (item.camera_id === this.monitorArr[this.monitorIndex]) {
            videojs(`video${this.monitorIndex}`, this.options, function () {
              this.dispose()
            })
            this.monitorArr[this.monitorIndex] = null
            this.$set(item, 'is_check', false)
            if (this.isShow) {
              this.closeMonitor()
            }
          } else {
            for (let i = 0; i < this.monitorArr.length; i++) {
              if (this.monitorArr[i] == item.camera_id) {
                if (document.getElementById(`video${i}`)) {
                  videojs(`video${i}`, this.options, function () {
                    this.dispose()
                  })
                  this.monitorArr[i] = null
                  break
                }
              }
            }
            this.monitorRequest(item, 1)
          }
        } else {
          this.monitorRequest(item, 1)
        }
      } else {
        this.$message.warning('请选择右侧视频放置区域')
      }
    },
    monitorRequest (item, val) {
      this.isLoading = true
      this.$http.get(`api/v1/security/monitor?camera_id=${item.camera_id}`)
        .then((res) => {
          this.isLoading = false
          this.monitorArr[this.monitorIndex] = item.camera_id
          if (document.getElementById(`video${this.monitorIndex}`)) {
            videojs(`video${this.monitorIndex}`, this.options, function () {
              this.dispose()
            })
            setTimeout(() => {
              this.init(res.data.url)
            }, 100)
          } else {
            this.init(res.data.url)
          }
          if (val) {
            for (let k = 0; k < this.monitorList.length; k++) {
              this.$set(this.monitorList[k], 'is_check', false)
              for (let j = 0; j < this.monitorArr.length; j++) {
                if (this.monitorArr[j]) {
                  if (this.monitorList[k].camera_id === this.monitorArr[j]) {
                    this.$set(this.monitorList[k], 'is_check', true)
                    break
                  }
                }
              }
            }
          } else {
            this.$set(item, 'is_check', true)
          }
          if (this.isShow) {
            videojs(`monitor0`, this.options, function () {
              this.dispose()
            })
            this.monitorCheck(item.camera_id)
          }
        })
        .catch(() => {
          this.isLoading = false
        })
    },
    monitorItemBtn (index) {
      this.monitorIndex = index
    },
    // 画面切割
    segmentationBtn (val) {
      if (val > this.segmentation) {
        for (let i = 0; i < val - this.segmentation; i++) {
          this.monitorArr.push(null)
        }
        this.closeMonitor()
      } else if (val < this.segmentation) {
        this.monitorArr.forEach((item, index) => {
          if (index + 1 > val) {
            if (document.getElementById(`video${index}`)) {
              videojs(`video${index}`, this.options, function () {
                this.dispose()
              })
            }
            if (item) {
              for (let i = 0; i < this.monitorList.length; i++) {
                if (this.monitorList[i].camera_id == item) {
                  this.monitorList[i].is_check = false
                }
              }
            }
          }
        })
        this.monitorArr = this.monitorArr.splice(0, val)
        this.closeMonitor()
      }
      this.monitorIndex = ''
      this.segmentation = val
    },
    // 选中某一个摄像头
    monitorCheck (item) {
      if (item) {
        this.isLoading = true
        this.$http.get(`api/v1/security/monitor?camera_id=${item}&streamType=0`)
          .then((res) => {
            this.isShow = true
            var myVideoDiv = document.getElementById('monitor')
            var tagName = document.createElement('video')
            var sourceTagName = document.createElement('source')
            sourceTagName.setAttribute('src', res.data.url)
            sourceTagName.setAttribute('type', 'application/x-mpegURL')
            tagName.className = 'video-js vjs-default-skin vjs-big-play-centered'
            tagName.setAttribute('id', `monitor0`)
            tagName.appendChild(sourceTagName)
            myVideoDiv.appendChild(tagName)
            videojs(`monitor0`, this.options, function () {
              this.play()
            })
            this.isLoading = false
          })
          .catch(() => {
            this.isLoading = false
          })
      }
    },
    // 搜索监控通道
    search () {
      if (this.monitorSearchValue) {
        const arr = []
        this.monitorTotalList.forEach((item) => {
          this.$set(item, 'is_check', false)
          if (item.name.indexOf(this.monitorSearchValue) != -1) {
            if (this.monitorArr.length > 0) {
              for (let i = 0; i < this.monitorArr.length; i++) {
                if (item.camera_id === this.monitorArr[i]) {
                  this.$set(item, 'is_check', true)
                  break
                }
              }
            }
            arr.push(item)
          }
        })
        this.monitorList = arr
      } else {
        const arr = []
        this.monitorTotalList.forEach((item) => {
          this.$set(item, 'is_check', false)
          if (this.monitorArr.length > 0) {
            for (let i = 0; i < this.monitorArr.length; i++) {
              if (item.camera_id === this.monitorArr[i]) {
                this.$set(item, 'is_check', true)
                break
              }
            }
          }
          arr.push(item)
        })
        this.monitorList = arr
      }
    },
    // 保存方案
    savePlan () {
      if (this.planInfo) {
        // 更新方案
        this.$confirm(`确定确认更新？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            this.savePlanFun('put')
          })
          .catch(() => { })
      } else {
        this.dialogVisible = true
        this.$nextTick(() => {
          this.$refs.plan.resetFields()
        })
        this.planEdit = false
      }
    },
    closeMonitor () {
      if (document.getElementById(`monitor0`)) {
        this.isShow = false
        videojs(`monitor0`, this.options, function () {
          this.dispose()
        })
      }
    },
    // 新增方案
    savePlanConfirm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.planEdit) {
            this.dialogLoading = true
            this.$http.patch(`/api/v1/security/plan/${this.planInfo.id}`, {
              name: this.plan.name
            })
              .then(() => {
                this.$message.success('修改成功')
                this.planList[this.planIndex].name = this.plan.name
                this.dialogLoading = false
                this.dialogVisible = false
              })
              .catch(() => {
                this.dialogLoading = false
              })
          } else {
            this.savePlanFun('post')
          }
        }
      })
    },
    savePlanFun (val) {
      let temp = 1
      switch (this.segmentation) {
        case 4:
          temp = 1
          break
        case 9:
          temp = 2
          break
        case 16:
          temp = 3
          break
        case 25:
          temp = 4
          break
      }
      const bool = this.monitorArr.some((item) => {
        return item != ''
      })
      if (bool) {
        this.dialogLoading = true
        if (val === 'post') {
          this.$http[val]('/api/v1/security/plan/', {
            name: this.plan.name,
            plan: temp,
            monitor_list: this.monitorArr
          })
            .then((res) => {
              this.$message.success('方案保存成功')
              this.planList.push(res.data)
              this.dialogVisible = false
              this.dialogLoading = false
            })
            .catch(() => {
              this.dialogLoading = false
            })
        } else {
          this.$http[val](`/api/v1/security/plan/${this.planInfo.id}`, {
            name: this.planInfo.name,
            plan: temp,
            monitor_list: this.monitorArr
          })
            .then((res) => {
              this.$message.success('方案更新成功')
              this.dialogVisible = false
              this.dialogLoading = false
            })
            .catch(() => {
              this.dialogLoading = false
            })
        }
      } else {
        this.$message.warning('请选择监控点')
      }
    },
    // 选择方案
    checkPlan (item, index) {
      console.log(item)
      this.planInfo = item
      this.segmentation = item.monitor_list.length
      this.monitorArr.forEach((item, i) => {
        if (document.getElementById(`video${i}`)) {
          videojs(`video${i}`, this.options, function () {
            this.dispose()
          })
        }
      })
      setTimeout(() => {
        this.monitorArr = []
        this.monitorIndex = ''
        item.monitor_list.forEach((item, i) => {
          if (item.url) {
            this.monitorArr.push(item.camera_id)
            //   console.log(item.url)
            var myVideoDiv = document.getElementById('division').childNodes[i]
            var tagName = document.createElement('video')
            var sourceTagName = document.createElement('source')
            sourceTagName.setAttribute('src', item.url)
            sourceTagName.setAttribute('type', 'application/x-mpegURL')
            tagName.className = 'video-js vjs-default-skin vjs-big-play-centered'
            tagName.setAttribute('id', `video${i}`)
            tagName.appendChild(sourceTagName)
            myVideoDiv.appendChild(tagName)
            videojs(`video${i}`, this.options, function () {
              this.on('play', function () {
                console.log('视频开始播放')
              })
              this.play()
            })
          } else {
            this.monitorArr.push(null)
          }
        })
        // this.search();
      }, 100)
    },
    // 编辑方案名称
    editPlan (item, index) {
      this.hideDropdown = false
      this.dialogVisible = true
      this.planEdit = true
      this.planInfo = item
      this.planIndex = index
      this.plan.name = item.name
      this.$nextTick(() => {
        this.$refs.plan.clearValidate()
      })
    },
    // 删除方案
    delPlan (item, index) {
      this.hideDropdown = false
      this.$confirm(`确定要删除‘${item.name}’吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$http.delete(`/api/v1/security/plan/${item.id}`)
            .then(res => {
              this.$message.success('删除成功')
              this.planList.splice(index, 1)
              if (item.id === this.planInfo.id) {
                this.monitorArr.forEach((item, i) => {
                  if (document.getElementById(`video${i}`)) {
                    videojs(`video${i}`, this.options, function () {
                      this.dispose()
                    })
                  }
                })
                this.segmentation = 4
                this.planInfo = ''
                this.monitorList.forEach((item) => {
                  this.$set(item, 'is_check', false)
                })
              }
            })
            .catch(() => { })
        })
        .catch(() => { })
    }
  }
}
</script>
<style lang="scss" scoped>
.video-preView {
  display: flex;
  width: 100%;
  height: 100%;
  overflow: hidden;

  .video-tree {
    width: 300px;
    display: inline-block;
    vertical-align: top;
    height: 100%;
    overflow: auto;

    .video-tree-input {
      display: flex;
    }

    .video-device {
      width: 100%;
      display: flex;
      align-items: center;
      border: 1px solid #e5e5e5;
      box-sizing: border-box;

      .video-sum-device {
        padding: 0 12px;
        box-sizing: border-box;
      }

      .video-device-list {
        border-left: 1px solid #e5e5e5;
        box-sizing: border-box;
        padding: 6px 0;

        & > div {
          padding: 6px 12px;
          box-sizing: border-box;
        }
      }
    }

    .monitor-ul {
      width: 100%;

      .monitor-item,
      .monitor-item-active {
        width: 100%;
        padding: 8px 24px;
        box-sizing: border-box;
        cursor: pointer;
      }

      .monitor-item-active {
        color: #409eff;
      }
    }

    ::v-deep
      .el-tree--highlight-current
      .el-tree-node.is-current
      > .el-tree-node__content {
      color: #409eff;
    }
  }

  .video-play {
    width: calc(100% - 300px);
    overflow: auto;
    padding-left: 20px;

    .video-play-select {
      width: 100%;
      display: flex;
      justify-content: space-between;

      .select-main {
        ::v-deep .el-button:active {
          color: #333;
          border-color: #dcdfe6;
        }

        ::v-deep .el-button:hover {
          color: #333;
          border-color: #dcdfe6;
          background-color: #fff;
        }

        ::v-deep .el-button:focus {
          color: #333;
          border-color: #dcdfe6;
          background-color: #fff;
        }
      }
    }

    .video-list {
      width: 100%;
      height: calc(100% - 120px);
      margin-top: 20px;
      position: relative;

      ::v-deep .monitor {
        width: 100%;
        height: 100%;
        position: fixed;
        top: 0;
        left: 0;
        z-index: 10;

        .el-icon-close {
          position: absolute;
          top: 20px;
          right: 20px;
          cursor: pointer;
          color: #fff;
          z-index: 10;
          font-size: 36px;
        }
      }
    }

    .picture-segmentation {
      display: flex;
      justify-content: flex-end;

      .segmentation-icon {
        display: flex;
        flex-direction: column;
        align-items: center;

        & > i {
          font-size: 40px;
        }
      }
    }
  }
}

.dropdown-item,
.dropdown-item-active {
  min-width: 150px;
  display: flex;
  justify-content: space-between;
  align-items: center;

  .dropdown-item-icons {
    display: flex;
    align-items: center;

    & > i {
      font-size: 18px;
    }

    .el-icon-delete {
      margin: 0;
    }
  }
}

.dropdown-item-active {
  color: #409eff;
}

.division {
  width: 40px;
  height: 40px;
  border-left: 1px solid #777;
  border-bottom: 1px solid #777;
  box-sizing: border-box;
  cursor: pointer;
}

.division-two,
.division-three,
.division-four,
.division-five {
  width: 100%;
  height: 100%;
  display: flex;
  flex-wrap: wrap;

  & > div {
    width: 50%;
    height: 50%;
    background: #333;
    border-top: 1px solid #777;
    box-sizing: border-box;
    border-right: 1px solid #777;
    cursor: pointer;
    position: relative;
  }

  & > div::after {
    content: '单击选中分屏，双击选中监控点';
    color: #777;
    font-size: 12px;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    position: absolute;
    left: 0;
    top: 0;
  }

  .monitor-item-active {
    border: 1px solid red;
  }

  .monitor-after-none::after {
    content: '';
  }
}

.division-three {
  & > div {
    width: 33.33%;
    height: 33.33%;
  }
}

.division-four {
  & > div {
    width: 25%;
    height: 25%;
  }
}

.division-five {
  & > div {
    width: 20%;
    height: 20%;
  }
}

.division-main {
  display: flex;
  justify-content: space-between;

  & > div {
    & > div {
      & > div::after {
        content: '' !important;
      }
    }
  }
}

::v-deep .vjs-fluid {
  height: 100%;
  padding-top: 0;
  overflow: hidden;
}
</style>
